package com.project.service.impl;

import com.project.bean.UserBean;
import com.project.mapper.IUserMapper;
import com.project.service.IUserService;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class UserServiceImpl extends BaseService implements IUserService {
    @Override
    public UserBean login(String userName, String psw) {
        SqlSession session = this.getSession();
        IUserMapper mapper = session.getMapper(IUserMapper.class);
        UserBean user = mapper.login(userName,psw);
        session.close();
        return user;
    }

    @Override
    public List<UserBean> FindALL() {
        SqlSession session = this.getSession();
        IUserMapper mapper = session.getMapper(IUserMapper.class);
        List<UserBean> list = mapper.FindALL();
        session.close();
        return list;
    }

    @Override
    public boolean addUser(UserBean userBean) {
        SqlSession session = this.getSession();
        IUserMapper mapper = session.getMapper(IUserMapper.class);
        if (mapper.findUserName(userBean.getUserName())!=null){
            return false;
        }
        mapper.addUser(userBean);
        session.commit();
        session.close();
        return true;
    }

    @Override
    public void delUser(Integer id) {
        SqlSession session = this.getSession();
        IUserMapper mapper = session.getMapper(IUserMapper.class);
        mapper.delUser(id);
        session.commit();
        session.close();
    }

    @Override
    public UserBean findById(Integer id) {
        SqlSession session = this.getSession();
        IUserMapper mapper = session.getMapper(IUserMapper.class);
        UserBean user = mapper.findById(id);
        session.close();
        return user;
    }

    @Override
    public void updateLevel(Integer id, String newLevel) {
        SqlSession session = this.getSession();
        IUserMapper mapper = session.getMapper(IUserMapper.class);
        mapper.updateLevel(id,newLevel);
        session.commit();
        session.close();
    }

    @Override
    public String updatePsw(UserBean loginUser, String oldPsw, String newPsw, String rNewPsw) {
        SqlSession session = this.getSession();
        IUserMapper mapper = session.getMapper(IUserMapper.class);
        if (oldPsw.equals(loginUser.getPsw())==false){
            return "旧密码错误";
        }
        if (newPsw.equals(rNewPsw)==false){
            return "两次密码不一致";
        }
        mapper.updatePsw(loginUser.getId(),rNewPsw);
        session.commit();
        session.close();
        return null;
    }
}
